package com.chuangzhi.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.chuangzhi.realm.AccountRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.swing.*;
import java.util.HashMap;
import java.util.Map;

//说白就是过滤器配置类 为realm配置
//创建3个Bean realm放manager manager放factoryBean
//shiro整合Thymeleaf（有授权的显示,没有的不显示）
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(defaultWebSecurityManager);
        //认证设置
        Map<String, String> map = new HashMap<>();
        map.put("/main","authc");  //访问main 必须是登录状态
        map.put("/manage","perms[manage]");  //访问manage 必须有manage权限
        map.put("/administator","roles[administator]");  //访问manage 必须有administator登录角色
        factoryBean.setFilterChainDefinitionMap(map);

        //设置登录页面 跳转login。html 页面
        factoryBean.setLoginUrl("/login");
        //设置未授权页面
        factoryBean.setUnauthorizedUrl("/unauth");
        return factoryBean;
    }

    //添加参数(@Qualifier("accountRealm") AccountRealm accountRealm)  将realm注入到DefaultWebSecurityManager
    //@Qualifier 作用是通过指定名字从IOC中获取Bean
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("accountRealm") AccountRealm accountRealm){
        //创建
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(accountRealm);
        return  manager;
    }


    //注入realm 已经注入到IOC中 默认方法名为注入到IOC中Bean的名字
    @Bean
    public AccountRealm accountRealm(){
        return new AccountRealm();
    }

    //shiro整合Thymeleaf（有授权的显示,没有的不显示）
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
}
